import { reqLogin, reqGetUserInfo, reqGetUserDetailById } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
const state = {
  token: getToken() || '',
  userInfo: {}
}
const mutations = {
  setToken(state, newToken) {
    // 存vuex
    state.token = newToken
    // 存本地s
    setToken(newToken)
  },
  removeToken(state) {
    state.token = ''
    removeToken()
  },
  setUserInfo(state, newUserInfo) {
    state.userInfo = newUserInfo
  },
  removeUserInfo(state) {
    state.userInfo = {}
  }
}
const actions = {
  async login(cxt, data1) {
    // const { data: { data }} = await reqLogin(data1)
    const res = await reqLogin(data1)
    // console.log(data)
    const newToken = res.data
    cxt.commit('setToken', newToken)
  },
  async getUserInfo(cxt) {
    const { data: data1 } = await reqGetUserInfo()
    const { data: data2 } = await reqGetUserDetailById(data1.userId)
    const res = {
      ...data1,
      ...data2
    }
    cxt.commit('setUserInfo', res)
    return res
  },
  logout(cxt) {
    cxt.commit('removeToken')
    cxt.commit('removeUserInfo')
  }
}
const getters = {}
export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}
